package com.jarvis.hospital.login;


import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.jarvis.hospital.MainActivity;
import com.jarvis.hospital.R;
import com.jarvis.hospital.common.BaseActivity;
import com.jarvis.hospital.common.ResponseData;
import com.jarvis.hospital.login.model.LoginModel;
import com.jarvis.hospital.login.model.UserModel;
import com.jarvis.hospital.patient.MainPatientActivity;
import com.jarvis.hospital.prescription.AllPrescriptionListActivity;
import com.jarvis.hospital.prescription.BloodDoneListActivity;
import com.jarvis.hospital.prescription.MedicineStockLogActivity;
import com.jarvis.hospital.servers.ApiService;
import com.jarvis.hospital.util.DateUtil;
import com.jarvis.hospital.util.JCountDownTimer;
import com.jarvis.hospital.util.SharePreferenceKey;
import com.jarvis.hospital.util.SharePreferenceUtils;
import com.jarvis.hospital.util.UpdateManager;
import com.jarvis.hospital.util.Util;
import com.jarvis.hospital.util.VersionManager;
import com.jarvis.hospital.util.net.RequestApi;

import java.util.HashSet;
import java.util.Set;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


public class LoginActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.tv_login)
    TextView tv_login;
    @BindView(R.id.rel_send)
    RelativeLayout rel_send;
    @BindView(R.id.tv_send)
    TextView tv_send;
    @BindView(R.id.ed_phone)
    EditText ed_phone;
    @BindView(R.id.ed_idenfy)
    EditText ed_idenfy;
    private ApiService service;
    private String phone;
    private String idenfy;
    private MyCountDown countDown;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initData() {
        countDown = new MyCountDown(60000, 1000);
    }

    @Override
    public void initView() {
        SharePreferenceUtils.putString(SharePreferenceKey.VERSION, VersionManager.getVersionName(this));
        setListener();
        service = RequestApi.create(ApiService.class);
        if (isLogin()) {
            Bundle bundle = new Bundle();
            bundle.putBoolean("isAuto", true);
            UserModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class).getUserInfo();
            String userRole = userModel.getUserRole();
            if ("dutynurse".equals(userRole)) {
                startActivity(AllPrescriptionListActivity.class, bundle);
            } else if ("docimaster".equals(userRole)) {
                startActivity(BloodDoneListActivity.class, bundle);
            } else if ("patient".equals(userRole)) {
                startActivity(MainPatientActivity.class, bundle);
            }else  if ("doctor".equals(userRole) || "clinicalPharmacist".equals(userRole)){
                startActivity(MainActivity.class, bundle);
            }else  if ("pharmacyPharmacist".equals(userRole)){
                startActivity(MedicineStockLogActivity.class, bundle);
            }else {
                showTextToast("该角色不存在");
                return;
            }
            finish();
        } else {
//            UpdateManager manager = new UpdateManager(this);
//            manager.checkUpdate();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (countDown != null && countDown.isRunning()) {
            countDown.reStart();

        }
    }

    @Override
    protected void onStop() {

        if (countDown != null && countDown.isRunning()) {
            countDown.pause();

        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        if (countDown != null) {
            countDown.cancel();
        }
        super.onDestroy();
    }

    private void setListener() {
        tv_login.setOnClickListener(this);
        rel_send.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_login:
                //startActivity(MainCounselorActivity.class);
                checkLogin();
                break;
            case R.id.rel_send:
                checkMobile();
                break;
        }
    }

    private void checkMobile() {
        phone = ed_phone.getText().toString();
        idenfy = ed_idenfy.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            showTextToast("电话号码不能为空");
        } else if (!Util.match("^((13[0-9])|(15[^4])|(18[0,1,2,3,5-9])|(17[0-8])|(147))\\d{8}$", phone)) {
            showTextToast("请输入正确的手机号码");
        } else {
            getIdenfy();
        }
    }

    public void checkLogin() {
        phone = ed_phone.getText().toString();
        idenfy = ed_idenfy.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            showTextToast("电话号码不能为空");
        } else if (TextUtils.isEmpty(idenfy)) {
            showTextToast("验证号码不能为空");
        } else if (!Util.match("^((13[0-9])|(15[^4])|(18[0,1,2,3,5-9])|(17[0-8])|(147))\\d{8}$", phone)) {
            showTextToast("请输入正确的手机号码");
        } else {
            doLogin();
        }
    }

    public void getIdenfy() {
        showDialog("loading");
        String currentTime = DateUtil.getInstance().getCurrentDate();
        String phone_4 = phone.substring(phone.length() - 4, phone.length());
        String SecretToken = Util.getSecretToken(currentTime, phone_4);
        service.sendSms(phone, currentTime, SecretToken)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData loginModelResponseData) {
                        if (loginModelResponseData != null) {
                            int resultCode = loginModelResponseData.getResultCode();
                            if (resultCode == 200) {
                                countDown.start();
                                rel_send.setEnabled(false);
                                tv_send.setTextColor(LoginActivity.this.getResources().getColor(R.color.gray_1));
                                showTextToast("验证码已发送，请注意查收");
                            } else {
                                showTextToast(loginModelResponseData.getMessage());
                            }
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        disMiss();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        disMiss();
                    }
                });

    }

    public void doLogin() {
        showDialog("加载中");
        service.doLogin(phone, idenfy, "0")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData<LoginModel>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData<LoginModel> loginModelResponseData) {
                        if (loginModelResponseData != null) {
                            int resultCode = loginModelResponseData.getResultCode();
                            if (resultCode == 200) {
                                SharePreferenceUtils.putObject(SharePreferenceKey.LOGIN_MODEL, loginModelResponseData.getData());
                                Bundle bundle = new Bundle();
                                bundle.putBoolean("isAuto", false);

                                UserModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class).getUserInfo();
                                String userRole = userModel.getUserRole();
//                                Set<String> tag = new HashSet<String>();
//                                tag.add("8888");
//                                JPushInterface.setTags(LoginActivity.this,Integer.parseInt(userModel.getUserId()),tag);
                                JPushInterface.setAlias(LoginActivity.this,Integer.parseInt(userModel.getUserId()),phone);
                                if ("dutynurse".equals(userRole)) {
                                    startActivity(AllPrescriptionListActivity.class, bundle);
                                } else if ("docimaster".equals(userRole)) {
                                    startActivity(BloodDoneListActivity.class, bundle);
                                }  else if ("patient".equals(userRole)) {
                                    bundle.putString("type","task");
                                    startActivity(MainPatientActivity.class, bundle);
                                } else  if ("doctor".equals(userRole) || "clinicalPharmacist".equals(userRole)){
                                    startActivity(MainActivity.class, bundle);
                                }else  if ("pharmacyPharmacist".equals(userRole)){
                                    startActivity(MedicineStockLogActivity.class, bundle);
                                }else {
                                    showTextToast("该角色不存在");
                                    return;
                                }
                                finish();
                            } else {
                                showTextToast(loginModelResponseData.getMessage());
                            }
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        disMiss();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        disMiss();
                    }
                });

    }

    public class MyCountDown extends JCountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public MyCountDown(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tv_send.setText(millisUntilFinished / 1000 + "s");
        }

        @Override
        public void onFinish() {
            tv_send.setText("发送验证码");
            tv_send.setTextColor(LoginActivity.this.getResources().getColor(R.color.white));
            rel_send.setEnabled(true);
        }
    }
}
